<?php

namespace JingdongApi\Models;

/**
 * API结果模型
 * 
 * @package JingdongApi\Models
 */
class ApiResult
{
    /**
     * 是否成功
     * @var bool
     */
    public $success;
    
    /**
     * 响应码
     * @var int
     */
    public $code;
    
    /**
     * 响应消息
     * @var string
     */
    public $message;
    
    /**
     * 响应数据
     * @var array|null
     */
    public $data;
    
    /**
     * 请求ID
     * @var string
     */
    public $requestId;
    
    /**
     * 构造函数
     * 
     * @param bool $success 是否成功
     * @param int $code 响应码
     * @param string $message 响应消息
     * @param array|null $data 响应数据
     * @param string $requestId 请求ID
     */
    public function __construct($success = false, $code = 0, $message = '', $data = null, $requestId = '')
    {
        $this->success = $success;
        $this->code = $code;
        $this->message = $message;
        $this->data = $data;
        $this->requestId = $requestId;
    }
    
    /**
     * 创建成功结果
     * 
     * @param array|null $data 响应数据
     * @param string $message 成功消息
     * @param string $requestId 请求ID
     * @return static
     */
    public static function success($data = null, $message = '请求成功', $requestId = '')
    {
        return new static(true, 0, $message, $data, $requestId);
    }
    
    /**
     * 创建失败结果
     * 
     * @param int $code 错误码
     * @param string $message 错误消息
     * @param array|null $data 响应数据
     * @param string $requestId 请求ID
     * @return static
     */
    public static function error($code, $message, $data = null, $requestId = '')
    {
        return new static(false, $code, $message, $data, $requestId);
    }
    
    /**
     * 从API响应创建结果
     * 
     * @param array $response API响应数组
     * @return static
     */
    public static function fromResponse($response)
    {
        $code = $response['code'] ?? -1;
        $message = $response['message'] ?? '未知错误';
        $data = $response['data'] ?? null;
        $requestId = $response['request_id'] ?? '';
        $success = $code === 0;
        
        return new static($success, $code, $message, $data, $requestId);
    }
    
    /**
     * 转换为数组
     * 
     * @return array
     */
    public function toArray()
    {
        return [
            'success' => $this->success,
            'code' => $this->code,
            'message' => $this->message,
            'data' => $this->data,
            'request_id' => $this->requestId
        ];
    }
    
    /**
     * 转换为JSON字符串
     * 
     * @return string
     */
    public function toJson()
    {
        return json_encode($this->toArray(), JSON_UNESCAPED_UNICODE);
    }
    
    /**
     * 魔术方法 - 转换为字符串
     * 
     * @return string
     */
    public function __toString()
    {
        return $this->toJson();
    }
}
